# import requests
# import base64
# import json
# import logging
# from src.utils.save_wave_file import save_wave_file
# from src.config import API_KEY, SECRET_KEY, APP_ID

# def get_access_token():
#     # 获取Access Token
#     auth_url = "https://aip.baidubce.com/oauth/2.0/token"
#     params = {
#         'grant_type': 'client_credentials',
#         'client_id': API_KEY,
#         'client_secret': SECRET_KEY
#     }
#     response = requests.post(auth_url, data=params)
#     if response:
#         return response.json().get('access_token')
#     return None

# def recognize_audio(audio_chunks):
#     logging.info('recognize_audio...')
#     if not audio_chunks:
#         logging.warning('没有音频数据')
#         return None

#     # 检查audio_chunks确保它是一个列表
#     if not isinstance(audio_chunks, list):
#         logging.warning('audio_chunks不是一个列表。')
#         return None
    
#     # 合并列表中的所有字节序列
#     audio_data = b''.join(audio_chunks)

#     file_path = save_wave_file(audio_data, "recive_audio_records")  # 保存音频数据

#     access_token = get_access_token()
#     if not access_token:
#         return "无法获取Access Token"

#     # 将音频数据转换为Base64编码
#     audio_base64 = base64.b64encode(audio_data).decode('utf-8')

#     # 设置API URL
#     recognize_url = f"https://vop.baidu.com/server_api"

#     # 构建请求参数
#     data = {
#         'format': 'wav',    # 根据实际音频格式调整
#         'rate': 16000,      # 根据实际音频采样率调整
#         # 'dev_pid': 1737,    # 根据需要选择语言和模型，英文
#         'dev_pid': 1536,          # 中文
#         'channel': 1,       # 对于单声道音频设置为1
#         'speech': audio_base64,
#         'cuid': APP_ID,
#         'token': access_token,
#         'len': len(audio_data)
#     }

#     # 发送请求
#     response = requests.post(recognize_url, data=json.dumps(data), headers={'Content-Type': 'application/json'})

#     if response:
#         result_json = response.json()
#         logging.info(result_json)
#         if 'result' in result_json:
#             return '\n'.join(result_json['result'])
#         else:
#             return "识别失败：" + result_json.get('err_msg', '')
#     return "API请求失败"


import aiohttp
import base64
import json
import logging
from src.utils.save_wave_file import save_wave_file
from src.config import API_KEY, SECRET_KEY, APP_ID

async def get_access_token():
    auth_url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {
        'grant_type': 'client_credentials',
        'client_id': API_KEY,
        'client_secret': SECRET_KEY
    }
    async with aiohttp.ClientSession() as session:
        async with session.post(auth_url, data=params) as response:
            if response.status == 200:
                data = await response.json()
                return data.get('access_token')
    return None

async def recognize_audio(audio_chunks):
    logging.info('recognize_audio...')
    if not audio_chunks:
        logging.warning('没有音频数据')
        return None

    if not isinstance(audio_chunks, list):
        logging.warning('audio_chunks不是一个列表。')
        return None
    
    audio_data = b''.join(audio_chunks)
    file_path = await save_wave_file(audio_data, "recive_audio_records")

    access_token = await get_access_token()
    if not access_token:
        return "无法获取Access Token"

    audio_base64 = base64.b64encode(audio_data).decode('utf-8')
    recognize_url = "https://vop.baidu.com/server_api"

    data = {
        'format': 'wav',
        'rate': 16000,
        'dev_pid': 1536,
        'channel': 1,
        'speech': audio_base64,
        'cuid': APP_ID,
        'token': access_token,
        'len': len(audio_data)
    }

    async with aiohttp.ClientSession() as session:
        async with session.post(recognize_url, data=json.dumps(data), headers={'Content-Type': 'application/json'}) as response:
            if response.status == 200:
                result_json = await response.json()
                logging.info(result_json)
                if 'result' in result_json:
                    return '\n'.join(result_json['result'])
                else:
                    return "识别失败：" + result_json.get('err_msg', '')
    return "API请求失败"
